// stores/login.js
import { defineStore } from 'pinia';
import axios from 'axios';
import { useUserStore } from './user';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { ref } from 'vue';

export const useLoginStore = defineStore('login', () => {
  const url = ref('');
  const sessionKey = ref('');
  const loading = ref(false);
  const ticket = ref('');
  const expired = ref(false); 
  const heartBeat = ref(0);
  let timer = null;
  const router = useRouter();
  const userStore = useUserStore();
  userStore.initializeUser();


  const apichecklogin = async (a) => {
    try {
      const res = await axios.get(`http://162.14.66.132/mp/qrcode/check?sessionKey=${a}`);
      if (res.data.code == 0 && res.data.data) {
        clearInterval(timer);
        
        ticket.value = res.data.data;
        getapits(ticket.value);
      } else if (res.data.code == 20501) {
        clearInterval(timer);
        expired.value = true;
        message.warning('二维码已过期，请重新获取');
      } 
    } catch (error) {
      clearInterval(timer);
      resetLoginState();
    }
  };


  const getapits = async (a) => {
    try {
      const res = await axios.get(`http://162.14.66.132/?ticket=${a}`);
      if (res.data.code == 0) {
        const userData = res.data.data;
        const tokenList = userData.loginTokenList;
        const token = tokenList && tokenList.length > 0 ? tokenList[0] : '';

        const userInfo = {
          username: userData.nickname,
          signature: userData.signature || '',
          token: token,
        };

        userStore.login(userInfo);
        console.log("userInfo.",userInfo)
        message.success('登录成功');
        resetLoginState();
      } else if (res.data.code == 20501) {
        message.error('登录已过期，请重新登录');
        resetLoginState();
        expired.value = true;
      } else {
        message.error(res.data.msg || '登录失败');
        resetLoginState();
      }
    } catch (error) {
      console.log(error)
      message.error('登录请求失败');
      resetLoginState();
    }
  };
  
  const resetLoginState = () => {
    url.value = '';
    sessionKey.value = '';
    loading.value = false;
    ticket.value = '';
    expired.value = false; 
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };

  const apicode = async () => {
    loading.value = true;
    expired.value = false; 
    try {
      const res = await axios.get('http://162.14.66.132/mp/qrcode');
      if (res.data.code == 0) {
        url.value = res.data.data.url;
        sessionKey.value = res.data.data.sessionKey;
        heartBeat.value = res.data.data.heartBeat;
        loading.value = false;

        timer = setInterval(() => {
          apichecklogin(sessionKey.value);
        }, heartBeat.value * 1000);
      } else {
        loading.value = false;
        message.error(res.data.msg || '获取二维码失败');
      }
    } catch (error) {
      loading.value = false;
      message.error('获取二维码失败');
    }
  };

  const retryQRCode = () => {
    resetLoginState();
    apicode();
  };


  const logout = () => {
    userStore.logout();
    message.success('已退出登录');
  };

  return {
    url,
    sessionKey,
    loading,
    ticket,
    apicode,
    logout,
    expired,
    retryQRCode, 
    resetLoginState
  };
});
